package com.org.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.org.common.PageBean;
import com.org.common.Result;
import com.org.pojo.Collect;
import com.org.pojo.CommunityBanner;
import com.org.pojo.CommunityMessage;
import com.org.service.ICommunityMessageService;
import com.org.service.NormalUserService;
import com.org.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cjx
 * @since 2024-03-03
 */
@RestController
@RequestMapping("/community-message")
public class CommunityMessageController {

    @Autowired
    private ICommunityMessageService communityMessageService;

    @Autowired
    private NormalUserService normalUserService;

    // 增
    @PostMapping("/add")
    public Result addCommunityMessage(@RequestBody CommunityMessage communityMessage) {
        Map<String, Object> param = ThreadLocalUtil.get();
        Integer userId = (Integer) param.get("id");

        if(communityMessage.getType() == null){
            communityMessage.setType(0);
        }
        communityMessage.setUserId(userId);
        communityMessage.setCreateTime(LocalDateTime.now());
        communityMessage.setName(normalUserService.getById(userId).getName());
        communityMessage.setUserAvatar(normalUserService.getById(userId).getUserPic());
        communityMessage.setCommunityId(normalUserService.getById(userId).getCommunityId());
        return communityMessageService.save(communityMessage) ? Result.success(communityMessage) : Result.error("添加留言失败");
    }

    // 删
    @GetMapping("/delete")
    public Result deleteCommunityMessage(long id) {
        return communityMessageService.removeById(id) ? Result.success("删除成功") : Result.error("删除留言失败");
    }

    // 改
//    @PostMapping("/update")
//    public Result updateCommunityMessage(@RequestBody CommunityMessage communityMessage) {
//        communityMessage.setUpdateTime(LocalDateTime.now());
//        return communityMessageService.updateById(communityMessage) ? Result.success(communityMessageService) : Result.error("修改留言失败");
//    }

    // 查
    @GetMapping("/detail")
    public Result getCommunityMessage(long id) {
        CommunityMessage communityMessage = communityMessageService.getById(id);
        communityMessage.setName(normalUserService.getById(communityMessage.getUserId()).getName());
        communityMessage.setUserAvatar(normalUserService.getById(communityMessage.getUserId()).getUserPic());
        return Result.success(communityMessage);
    }

    // 分页
    @GetMapping("/list")
    public Result<PageBean<CommunityMessage>> getCommunityMessages(
            Integer pageNum,    //第几页
            Integer pageSize,   //页面容量
            String communityId, //社区id 不可为空，因为用户只能查看自己社区的留言，社区管理员也是
            Boolean isUp,        //true：按时间升序排序，false：降序 不可为空
            String userId,     //用户id 可为空，可不传
            String type        //类型 0普通留言 1给社区管理员的提议，但是还没有被处理 2给社区管理员的提议，并且已经被管理员处理了 可为空，可不传
    ) {

        Page<CommunityMessage> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        LambdaQueryWrapper<CommunityMessage> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CommunityMessage::getCommunityId, communityId);
        // isUp 为真，则按时间升序
        lambdaQueryWrapper.orderBy(isUp, true, CommunityMessage::getCreateTime);
        // 否则按时间降序
        lambdaQueryWrapper.orderBy(!isUp, false, CommunityMessage::getCreateTime);

        if (userId != null && !userId.isEmpty()) {
            lambdaQueryWrapper.eq(CommunityMessage::getUserId, userId);
        }

        if (type != null && !type.isEmpty()) {
            lambdaQueryWrapper.eq(CommunityMessage::getType, type);
        }

        IPage<CommunityMessage> iPage = communityMessageService.page(page, lambdaQueryWrapper);

        List<CommunityMessage> communityMessages = iPage.getRecords();
        for (CommunityMessage communityMessage : communityMessages) {
            communityMessage.setName(normalUserService.getById(communityMessage.getUserId()).getName());
            communityMessage.setUserAvatar(normalUserService.getById(communityMessage.getUserId()).getUserPic());
        }

        PageBean<CommunityMessage> pageBean = new PageBean<>();
        pageBean.setTotal(iPage.getTotal());
        pageBean.setItems(communityMessages);

        return Result.success(pageBean);
    }

    /**
     * 管理员处理用户留言
     * 传入 type 为1 的留言的 id，然后该接口将其更新type为1，表示管理员已经对该留言进行处理
     * 传入示例
     * {
     * "id": 1
     * }
     */
    @PostMapping("/handle")
    public Result adminHandleCommunityMessage(@RequestBody Map<String, Integer> map) {
        Integer id = map.get("id");
        CommunityMessage communityMessage = communityMessageService.getById(id);
        if (communityMessage.getType() == 1) {
            communityMessage.setType(2);
            return communityMessageService.updateById(communityMessage) ? Result.success("处理成功") : Result.error("处理失败");
        } else {
            return Result.error("传入参数非法");
        }
    }


}
